//
//  HMAudioPlayerController.m
//  MOMU
//
//  Created by mynSoo on 2017/1/3.
//  Copyright © 2017年 mynSoo. All rights reserved.
//

// 主框架
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>

// 工具
#import <UIView+SDExtension.h>
#import "UIColor+Addition.h"
#import "UIButton+JKImagePosition.h"
#import "UIViewController+Extension.h"
#import "MOPopWindow.h"

// 控制器
#import "HMAudioPlayerController.h"
#import "HMAudioPlayerListViewController.h"
#import "HMAudioPlayerTextViewController.h"
#import "HMAudioPlayerAudioTimerController.h"

// 功能
#import "HMAudioPlayer.h"
#import "DownloadManager.h"

// 控件
#import "HMLisenAudioLoadingView.h"
#import "HMAudioPlayerShareView.h"

#define BASE_TOP_MARGIN 64
#define BASE_MARGIN 16
#define AudioTitleLabel_TEXTSIZE 17
#define AudioTagLabel_TEXTSIZE 8

#define AudioCoverImageviewHeight 200
#define AudioCoverImageviewWidth 150

// 音频时间
// 听筒播放

typedef enum : NSInteger
{
    MoreButtonTypeRate = 0,
    MoreButtonTypeTimer = 1,
    MoreButtonTypeShare = 2,
    MoreButtonTypeBottomCancle = 4
    
}MoreButtonType;

typedef enum : NSInteger
{
    TabButtonTypeList = 0,
    TabButtonTypeText = 1,
    TabButtonTypeLike = 2,
    TabButtonTypeDownload = 3,
    TabButtonTypeMore = 4
    
}TabButtonType;

@interface HMAudioPlayerController () <UITabBarDelegate>
{
    NSInteger _audioIndex;
}

/// 播放器
@property (nonatomic, strong) AVPlayer *player;
/// 媒体文件播放总时长
@property (nonatomic, assign) float durationTime;
/// 媒体文件现在播放时间
@property (nonatomic, assign) float currentTime;
@property (nonatomic, strong) NSNumber *escapeTime;
/// 播放刷新计时器
@property (nonatomic, weak) NSTimer *timer;
/// URL缓存
@property (nonatomic, strong) NSArray<NSURL *>* urlArray;
///正在指向的URL下标
//@property (nonatomic, assign) NSInteger index;
/// 播放速率
@property (nonatomic, assign) float rate;
///声音大小
@property (nonatomic, assign) float volume;

#define kRateCount 6
@property (nonatomic, assign) NSInteger rateCondition;

@property (nonatomic, strong) id playTimeObserver; // 播放进度观察者
@property (nonatomic, assign) BOOL isRemoveNot; // 是否移除通知
@property (nonatomic, assign) BOOL playState;

@property (nonatomic, weak) UILabel *audioTitleLabel;
@property (nonatomic, weak) UILabel *audioTagLabel;
@property (nonatomic, weak) UIImageView *audioCoverImageview;

// AudioProgressBar
@property (nonatomic, weak) UISlider *progressSlider;
@property (nonatomic, weak) UILabel *progressCurrentLabel;
@property (nonatomic, weak) UILabel *progressDurationLabel;

// MediaControlButton
@property (nonatomic, weak) UIButton *left15secondBtn;
@property (nonatomic, weak) UIButton *right15secondBtn;
@property (nonatomic, weak) UIButton *previousBtn;
@property (nonatomic, weak) UIButton *nextBtn;
@property (nonatomic, weak) UIButton *playBtn;

typedef enum : NSInteger
{
    MoreLabelTypeRate = 0,
    MoreLabelTypeShare = 2,
    MoreLabelTypeTimer = 1,
}MoreLabelType;

@property (nonatomic, weak) UILabel *shareLabel;
@property (nonatomic, weak) UILabel *rateLabel;
@property (nonatomic, weak) UILabel *timerLabel;

// AudioTabbarView
@property (nonatomic, weak) UIView *audioTabBarView;
@property (nonatomic, weak) HMLisenAudioLoadingView *progressView;
@property (nonatomic, weak) UIButton *likeBtn;

// close Timer
@property (nonatomic, strong) NSTimer *closeTimer;
@property (nonatomic, assign) CGFloat closeTotalTime;
@property (nonatomic, weak) UIButton *downloadBtn;

@end

@implementation HMAudioPlayerController

#pragma mark - 初始化

static HMAudioPlayerController *_instance;

+ (instancetype)sharePlayer
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        // 初始化
        _instance = [[HMAudioPlayerController alloc] init];
    
    });
   
    return _instance;
}

- (instancetype)init
{
    self = [super init];
    if(self)
    {
        self.view.backgroundColor = [UIColor whiteColor];
        self.player = [[AVPlayer alloc]init];
        
        // 开始接受远程控制
        [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
        [self resignFirstResponder];
        
        // 接触远程控制
        // [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
        
        [self becomeFirstResponder];
        
        self.playState = NO;
        
        //处理中断事件的通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterreption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];
        // -->实现接收到中断通知时的方法
    }
    return self;
}

#pragma mark - 设置
// 各控件设初始值
- (void)initialControls
{
    
    [self stop];
    self.progressCurrentLabel.text = @"00:00";
    self.progressDurationLabel.text = @"00:00";
    self.progressSlider.value = 0.0f;
    
}

-(NSTimer *)timer
{
    
    if(!_timer)
    {
        NSTimer *timer = [NSTimer timerWithTimeInterval:0.5 target: self selector:@selector(intervalTimerAction) userInfo:nil repeats:YES];
        _timer = timer;
        [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
        
    }
    return _timer;
}

- (void)setProgressView:(UIView *)progressView // 准备废弃
{
    
    HMLisenAudioLoadingView *newProgressView = [[HMLisenAudioLoadingView alloc]init];
    
    [self.view addSubview:newProgressView];
    _progressView = newProgressView;

    [newProgressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.audioTabBarView.mas_top).offset(-30);
        
        make.width.offset([UIScreen mainScreen].bounds.size.width);
        make.height.offset(10);
        make.centerX.offset(0);
    }];
}

- (void)setPlayState:(BOOL)playState
{
    
    
    _playState = playState;
    
    [self updatePlayBtn:playState];
    
}

- (void)setModelArray:(NSArray *)modelArray
{
    // 设置播放序列
    _modelArray = modelArray;
    
    // 播放序号
    _audioIndex = 0;
    
    // 更新状态
    // [self updateAudioPlayer];
    
}

- (void)setModelArray:(NSArray *)array index:(NSInteger)index
{
    _modelArray = array;
    _audioIndex = index;
    if(index >= array.count)
    {
        _audioIndex = 0;
    }
}

-(BOOL)isPlaying
{
    return _playState;
}

#pragma mark - 响应

// 重写父类成为响应者方法
- (BOOL)canBecomeFirstResponder
{
    return YES;
}

- (void)remoteControlReceivedWithEvent:(UIEvent *)receivedEvent
{

    if (receivedEvent.type == UIEventTypeRemoteControl) {
        
        switch (receivedEvent.subtype) {
                
            case UIEventSubtypeRemoteControlTogglePlayPause: // 暂停
                [self.player pause];
            
                break;
                
            case UIEventSubtypeRemoteControlPreviousTrack:  // 上一首
                
                [self playPrevious];
                break;
                
            case UIEventSubtypeRemoteControlNextTrack: // 下一首
                [self playNext];
                break;
                
            case UIEventSubtypeRemoteControlPlay: //播放
                [self play];
                break;
                
            case UIEventSubtypeRemoteControlPause: // 暂停
                [self stop];
                break;
                
            default:
                break;
        }
    }
}

#pragma mark - 监听

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    
    AVPlayerItem *item = (AVPlayerItem *)object;
    
    if ([keyPath isEqualToString:@"status"]) {
        if ([self.player.currentItem status] == AVPlayerStatusReadyToPlay) {
           // NSLog(@"AVPlayerStatusReadyToPlay");
            CMTime duration = item.duration;// 获取视频总长度
            [self setMaxDuratuin:CMTimeGetSeconds(duration)];
            
            [self.player play];
            [self.timer setFireDate:[NSDate dateWithTimeIntervalSinceNow:0]];
            [self setLockViewWith:_playingModel currentTime:self.escapeTime.doubleValue];
            self.playState = YES;
            
            
        }else if([self.player.currentItem status] == AVPlayerStatusFailed) {
            //NSLog(@"AVPlayerStatusFailed");
            
            [self.player pause];
            [self setLockViewWith:_playingModel currentTime:self.escapeTime.doubleValue];
            self.playState = NO;
        }
    }
    
}

- (void)removeObserverAndNotification{
    __weak AVPlayerItem *item = self.player.currentItem;
    [self.player.currentItem removeObserver:self forKeyPath:@"status"];
//    [self.player.currentItem cancelPendingSeeks];
//    [self.player.currentItem.asset cancelLoading];
    [self.player replaceCurrentItemWithPlayerItem:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}

- (void)addEndTimeNotification{
    //给AVPlayerItem添加播放完成通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
}

#pragma mark - 完成时调用
- (void)playbackFinished:(NSNotification *)notification
{
    if(self.closeTotalTime == -1)
    {
        self.closeTotalTime = 0;
        
    }
    else
    {
        [self playNext];
    }
}

#pragma mark - 播放时循环调用 (更新)

- (void)intervalTimerAction
{
    
    self.escapeTime = @(CMTimeGetSeconds(self.player.currentTime));
    //[self setLockViewWith:_playingModel currentTime:self.escapeTime.doubleValue];
    [self updateVideoSlider:self.escapeTime.doubleValue];

}

#pragma mark - 更新
- (void)updateAudioPlayer{
    
    if (_isRemoveNot)
    {
        // 如果已经存在 移除通知、KVO，各控件设初始值
        [self removeObserverAndNotification];
        

        [self initialControls];
        _isRemoveNot = NO;
    }
    
    HMListenAnyTimeResModel *model;
    
    model = [_modelArray objectAtIndex:_audioIndex];
    
    self.playState = NO;
    
    self.playingModel = model;
    
    [self.player pause];
    
    [self setLockViewWith:_playingModel currentTime:CMTimeGetSeconds(self.player.currentTime)];
    
    [self updateUIWithModel:model];

    AVPlayerItem *playerItem;
    if(model.asset == nil)
    {
        AVURLAsset *asset = [AVURLAsset URLAssetWithURL:[NSURL URLWithString:model.audio_file_url] options:nil];
        
        model.asset = asset;
    }
    //playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:model.audio_file_url]];
    
    playerItem = [AVPlayerItem playerItemWithAsset:model.asset];
    
    [self.player replaceCurrentItemWithPlayerItem:playerItem];

    // 监听状态
    [playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];// 监听status属性
    
    [self addEndTimeNotification];
    self.isRemoveNot = YES;
}

#pragma mark update UI
- (void)updateUIWithModel:(HMListenAnyTimeResModel *)model;
{
    self.audioTitleLabel.text = model.resource_name;

    self.title = [NSString stringWithFormat:@"随时听 %ld / %ld",_audioIndex + 1,self.modelArray.count];
    
    if(model.image_url.length > 0)
    {
        NSURL *url = [NSURL URLWithString:model.image_url];
        if(url)
        {
            //[self.audioCoverImageview sd_setImageWithURL:url];
            [self.audioCoverImageview sd_setImageWithURL:url placeholderImage: [[UIImage alloc]init] options:SDWebImageProgressiveDownload];
        }
    }
    
}
- (void)updatePlayBtn:(BOOL)state
{
    if(state)
    {
        [self.playBtn setImage:[UIImage imageNamed:@"mediaplayer_parse_btn"] forState:UIControlStateNormal];
        [self.playBtn setImage:[UIImage imageNamed:@"mediaplayer_parse_btn_highselected"] forState:UIControlStateHighlighted];
    }
    else
    {
        [self.playBtn setImage:[UIImage imageNamed:@"mediaplayer_play_btn"] forState:UIControlStateNormal];
        [self.playBtn setImage:[UIImage imageNamed:@"mediaplayer_play_btn_highselected"] forState:UIControlStateHighlighted];
    }
    
}

- (void)updateVideoSlider:(CGFloat)currentTime{
    
    // [self setLockViewWith:_playingModel currentTime:currentTime];
    
    self.progressCurrentLabel.text = [NSString convertMin:currentTime];
    if(!self.progressSlider.state)
    {
        self.progressSlider.value = currentTime;
        
    }
}

#pragma mark - 更新后台UI
- (void)setLockViewWith:(HMListenAnyTimeResModel*)model currentTime:(CGFloat)currentTime
{
    if(!model)
    {
        return;
    }
    NSMutableDictionary *musicInfo = [NSMutableDictionary dictionary];
    // 设置Singer
    [musicInfo setObject:@"" forKey:MPMediaItemPropertyArtist];
    // 设置歌曲名
    [musicInfo setObject:model.resource_content forKey:MPMediaItemPropertyTitle];
    // 设置封面
    MPMediaItemArtwork *artwork;
    if(self.audioCoverImageview.image)
    {
        artwork = [[MPMediaItemArtwork alloc] initWithImage:self.audioCoverImageview.image];
        [musicInfo setObject:artwork forKey:MPMediaItemPropertyArtwork];
    }
    //音乐剩余时长
    [musicInfo setObject:[NSNumber numberWithDouble:self.durationTime] forKey:MPMediaItemPropertyPlaybackDuration];
    
    //音乐当前播放时间
    
    [musicInfo setObject:[NSNumber numberWithDouble:currentTime] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
    
    [musicInfo setObject:[NSNumber numberWithFloat:1.0] forKey:MPNowPlayingInfoPropertyPlaybackRate];
    
    [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:musicInfo];
}

- (void)setMaxDuratuin:(float)duration{
    _durationTime = duration;
    if(duration > 0)
    {
        self.progressSlider.maximumValue = duration;
    }
    self.progressDurationLabel.text = [NSString convertMin:duration];
}

#pragma mark - 初始化UI

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self installUI];
    
}

- (void)installUI
{
    [self setTitle];
    [self installAudioTitleLabel];
    [self installAudioTagLabel];
    [self installAudioCoverImageView];
    [self installAudioProgressBar];
    [self installAudioTabBar];
    [self installMediaControlButton];
    
    // [self installProgressView];
}

- (void)setTitle
{
    self.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    // UINavigationBar *navBar = self.navigationController.navigationBar;
    
    if(self.modelArray.count > 0)
    {
        self.title = [NSString stringWithFormat:@"随时听 %ld,%ld",_audioIndex,self.modelArray.count];
    }
    else
    {
        self.title = @"随时听 1/10";
    }

}

- (void)installAudioTitleLabel
{
    // 1.创建对象
    UILabel *audioTitleLabel = [[UILabel alloc]init];
    [self.view addSubview:audioTitleLabel];
    self.audioTitleLabel = audioTitleLabel;
    
    // 2.约束
    [audioTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(BASE_MARGIN + BASE_TOP_MARGIN);
        //make.centerX.equalTo(self.view);
        make.left.offset(20);
        make.right.offset(-20);
    }];
    
    // 3.配置属性
    audioTitleLabel.text = @"如何拥有持久的快乐"; //debug
    audioTitleLabel.textAlignment = NSTextAlignmentCenter;
    audioTitleLabel.textColor = [UIColor blackColor];
    audioTitleLabel.font = [UIFont systemFontOfSize:AudioTitleLabel_TEXTSIZE];

}

- (void)installAudioTagLabel
{
    // 1.创建对象
    UILabel *audioTagLabel = [[UILabel alloc]init];
    [self.view addSubview:audioTagLabel];
    self.audioTagLabel = audioTagLabel;
    
    // 2.约束
    [audioTagLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.audioTitleLabel.mas_bottom).offset(13);
        make.centerX.equalTo(self.view);
    }];
    
    // 3.配置属性
    //audioTagLabel.text = @"#思维 #心理学"; //debug
    audioTagLabel.textAlignment = NSTextAlignmentCenter;
    audioTagLabel.textColor = [UIColor grayColor];
    audioTagLabel.font = [UIFont systemFontOfSize:AudioTagLabel_TEXTSIZE];
}

- (void)installAudioCoverImageView
{
    // 创建对象
    UIImageView *audioCoverImageview = [[UIImageView alloc]init];
    self.audioCoverImageview = audioCoverImageview;
    [self.view addSubview:audioCoverImageview];
    
    // 约束
    [audioCoverImageview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.audioTagLabel.mas_bottom).offset(BASE_MARGIN);
        make.centerX.equalTo(self.view);
        make.height.offset(AudioCoverImageviewHeight);
        make.width.offset(AudioCoverImageviewWidth);
    }];
    
    // 配置信息
    audioCoverImageview.backgroundColor = [UIColor clearColor];
    audioCoverImageview.contentMode = UIViewContentModeScaleToFill;
}

- (void)installAudioProgressBar
{
    // 创建对象
    UISlider *progressSlider = [[UISlider alloc]init];
    self.progressSlider = progressSlider;
    [self.view addSubview:progressSlider];
    
    // 约束
    [progressSlider mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.audioCoverImageview.mas_bottom).offset(15);
        make.left.offset(24);
        make.right.offset(-24);
    }];
    // 配置
    [progressSlider setThumbImage:[UIImage imageNamed:@"mediaplayer_slider_btn"] forState:UIControlStateNormal];
    progressSlider.maximumTrackTintColor = [UIColor grayColor];
    progressSlider.minimumTrackTintColor = [UIColor colorWithHex:0xffa42f];
    // progressSlider
    [self.progressSlider addTarget:self action:@selector(changeProgress:) forControlEvents:UIControlEventTouchUpInside];
    
    // Current 创建
    UILabel *progressCurrentLabel = [[UILabel alloc]init];
    self.progressCurrentLabel = progressCurrentLabel;
    [self.view addSubview:progressCurrentLabel];
    
    // 约束
    [progressCurrentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(progressSlider);
        make.bottom.equalTo(progressSlider.mas_top).offset(-8);
    }];
    
    // 配置
    progressCurrentLabel.text = @"00:00"; // debug
    progressCurrentLabel.textAlignment = NSTextAlignmentCenter;
    progressCurrentLabel.font = [UIFont systemFontOfSize:10];
    progressCurrentLabel.textColor = [UIColor grayColor];
    
    // durantion
    
    UILabel *progressDurationLabel = [[UILabel alloc]init];
    self.progressDurationLabel = progressDurationLabel;
    [self.view addSubview:progressDurationLabel];
    // 约束
    [progressDurationLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(progressSlider);
        make.bottom.equalTo(progressSlider.mas_top).offset(-8);
    }];
    
    // 配置
    progressDurationLabel.text = @"00:00"; // debug
    progressDurationLabel.textAlignment = NSTextAlignmentCenter;
    progressDurationLabel.font = [UIFont systemFontOfSize:10];
    progressDurationLabel.textColor = [UIColor grayColor];
    
}

- (void)installProgressView
{
    HMLisenAudioLoadingView *progressView = [[HMLisenAudioLoadingView alloc]init];
    
    [self.view addSubview:progressView];
    self.progressView = progressView;
    // newProgressView.modelArr = self.modelArray;
    
    [progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.audioTabBarView.mas_top).offset(-30);
        
        make.width.offset([UIScreen mainScreen].bounds.size.width);
        make.height.offset(10);
        make.centerX.offset(0);

    }];
}

- (void)installAudioTabBar
{
    UIView *audioTabBarView = [[UIView alloc]init];
    self.audioTabBarView = audioTabBarView;
    [self.view addSubview:audioTabBarView];
    
    [audioTabBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.height.offset(44);
    }];
 
    UIButton *listBtn = [UIButton buttonWithType:0];
    [listBtn setImage:[UIImage imageNamed:@"mediaplayer_list_btn"] forState:UIControlStateNormal];

    UIButton *textBtn = [UIButton buttonWithType:0];
    [textBtn setImage:[UIImage imageNamed:@"mediaplayer_text_btn"] forState:UIControlStateNormal];
    
    UIButton *likeBtn = [UIButton buttonWithType:0];
    [likeBtn setImage:[UIImage imageNamed:@"mediaplayer_like_btn"] forState:UIControlStateNormal];
    [likeBtn setImage:[UIImage imageNamed:@"new_main_audio_liked_selected"]  forState:UIControlStateSelected];
    
    self.likeBtn = likeBtn;
    
    UIButton *downloadBtn = [UIButton buttonWithType:0];
    [downloadBtn setImage:[UIImage imageNamed:@"mediaplayer_download_btn"] forState:UIControlStateNormal];
    
    UIButton *moreBtn = [UIButton buttonWithType:0];
    [moreBtn setImage:[UIImage imageNamed:@"new_audio_more_btn"] forState:UIControlStateNormal];
    
    NSArray *btnArray = @[listBtn, textBtn, likeBtn ,downloadBtn, moreBtn];
    NSArray *btnTitle = @[@"列表", @"文稿", @"喜欢", @"下载", @"更多"];
    
    for(NSInteger i = 0; i < btnArray.count; i++)
    {
        UIButton *btn = btnArray[i];
        btn.titleLabel.font = [UIFont systemFontOfSize:12];
        [btn hm_setTitle:btnTitle[i] andTiTleColorWithHex:0xb3b3b3 forState:UIControlStateNormal];
        [btn jk_setImagePosition:LXMImagePositionTop spacing:3];
        [audioTabBarView addSubview:btn];
        btn.tag = i;
        [btn addTarget:self action:@selector(clickTabBarViewBtn:) forControlEvents:UIControlEventTouchDown];
    }
    
    [btnArray mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(audioTabBarView);
        make.height.equalTo(audioTabBarView);
    }];
    
    [btnArray mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:0 leadSpacing:0  tailSpacing:0];
    self.downloadBtn = btnArray[3];
    
}

- (void)installMediaControlButton;
{
    
    UIButton *playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.playBtn = playBtn;
    [self.view addSubview:playBtn];
    
    //mediaplayer_parse_btn_highselected

    [playBtn setImage:[UIImage imageNamed:@"mediaplayer_play_btn"] forState:UIControlStateNormal];
    [playBtn setImage:[UIImage imageNamed:@"mediaplayer_play_btn_highselected"] forState:UIControlStateHighlighted];
    
    [playBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.audioTabBarView.mas_top).offset(-65);
    }];

    [playBtn addTarget:self action:@selector(clickPlayBtn:) forControlEvents:UIControlEventTouchDown];
    
    // 创建
    //    @property (nonatomic, weak) UIButton *previousBtn;
    
    UIButton *left15secondBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.left15secondBtn = left15secondBtn;
    [self.view addSubview:left15secondBtn];
    [left15secondBtn setImage:[UIImage imageNamed:@"mediaplayer_15second_left"] forState:UIControlStateNormal];
    
    [left15secondBtn setTitleColor:[UIColor colorWithHex:0xcccccc] forState:UIControlStateNormal];
    [left15secondBtn setTitleColor:[UIColor colorWithHex:0x636363] forState:UIControlStateHighlighted];
    
    [left15secondBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(playBtn);
        make.right.equalTo(playBtn.mas_left).offset(-15);
    }];
    
    [left15secondBtn addTarget:self action:@selector(leftSeek15) forControlEvents:UIControlEventTouchDown];
    
    // 创建
    //    @property (nonatomic, weak) UIButton *nextBtn;
    UIButton *right15secondBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.right15secondBtn = right15secondBtn;
    [self.view addSubview:right15secondBtn];
    [right15secondBtn setImage:[UIImage imageNamed:@"mediaplayer_15second_right"] forState:UIControlStateNormal];
    
    [right15secondBtn setTitleColor:[UIColor colorWithHex:0xcccccc] forState:UIControlStateNormal];
    [right15secondBtn setTitleColor:[UIColor colorWithHex:0x636363] forState:UIControlStateHighlighted];
    
    [right15secondBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(playBtn);
        make.left.equalTo(playBtn.mas_right).offset(15);
    }];
    
    [right15secondBtn addTarget:self action:@selector(rightSeek15) forControlEvents:UIControlEventTouchDown];
    
    UIButton *previousBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.previousBtn = previousBtn;
    [self.view addSubview:previousBtn];
    [previousBtn setImage:[UIImage imageNamed:@"mediaplayer_last_btn"] forState:UIControlStateNormal];
    
    [previousBtn setTitleColor:[UIColor colorWithHex:0xcccccc] forState:UIControlStateNormal];
    [previousBtn setTitleColor:[UIColor colorWithHex:0x636363] forState:UIControlStateHighlighted];
    // previousBtn
    [previousBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(left15secondBtn);
        make.left.offset(15);
    }];
    [previousBtn addTarget:self action:@selector(clickPreviousBtn:) forControlEvents:UIControlEventTouchDown];
    
    // @property (nonatomic, weak) UIButton *nextSeekBtn;
    // mediaplayer_next_btn
    
    UIButton *nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.nextBtn = nextBtn;
    [self.view addSubview:nextBtn];
    [nextBtn setImage:[UIImage imageNamed:@"mediaplayer_next_btn"] forState:UIControlStateNormal];
    
    [nextBtn setTitleColor:[UIColor colorWithHex:0xcccccc] forState:UIControlStateNormal];
    [nextBtn setTitleColor:[UIColor colorWithHex:0x636363] forState:UIControlStateHighlighted];
    // previousBtn
    [nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(right15secondBtn);
        make.right.offset(-15);
    }];
    
    [nextBtn addTarget:self action:@selector(clickNextBtn:) forControlEvents:UIControlEventTouchDown];
    
}


- (UIView *)installButtomMoreView
{
    UIView *buttomMoreView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 225)];
    
    buttomMoreView.backgroundColor = [UIColor whiteColor];
    
    NSArray *imageStringArr = @[@"new_audio_rate1_btn", @"new_audio_timer_btn", @"new_audio_share_btn"];
    NSArray *titleArr = @[@"正常播放", @"定时关闭", @"分享"];
    
    NSMutableArray *btnArrM = [NSMutableArray array];
    NSMutableArray *labelArrM = [NSMutableArray array];
    for (NSInteger i = 0; i < imageStringArr.count; i++)
    {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        
        UILabel *label = [[UILabel alloc]init];
        btn.tag = i;
        label.tag = i;
        [buttomMoreView addSubview:btn];
        [buttomMoreView addSubview:label];
        //btn.bounds = CGRectMake(0, 50, 0, 100);
        
        [btn setImage:[UIImage imageNamed:imageStringArr[i]] forState:UIControlStateNormal];
        label.text = titleArr[i];
        
        label.font = [UIFont systemFontOfSize:15];
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor colorWithHex:0xbebebe];
        
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(btn.mas_bottom).offset(10);
            make.centerX.equalTo(btn);
        }];
        
        [btn addTarget:self action:@selector(clickButtomMoreViewBtn:) forControlEvents:UIControlEventTouchDown];
        
        
        [btnArrM addObject:btn];
        [labelArrM addObject:label];
        
    }
    self.rateLabel = labelArrM[MoreLabelTypeRate];
    self.shareLabel = labelArrM[MoreLabelTypeShare];
    self.timerLabel = labelArrM[MoreLabelTypeTimer];
    
    if(self.closeTotalTime > 0 )
    {
        self.timerLabel.text = [NSString convertMin:self.closeTotalTime];
        self.timerLabel.textColor = [UIColor colorWithHex:0xffa42f]; //需要改颜色
    }
    else if(self.closeTotalTime < 0)
    {
        self.timerLabel.text = @"播完这条";
        self.timerLabel.textColor = [UIColor colorWithHex:0xbebebe];
    }
    else
    {
        self.timerLabel.text = @"定时关闭";
        self.timerLabel.textColor = [UIColor colorWithHex:0xbebebe];
    }

    
    [self updateRateAction: btnArrM[0]];
    
    
    [btnArrM mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:0 leadSpacing:0 tailSpacing:0];
    
    
    [btnArrM mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(47);
        // make.height.offset(100);
    }];
    
    UIView *separatorView = [[UIView alloc]init];
    
    [buttomMoreView addSubview: separatorView];
    
    [separatorView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(171);
        make.height.offset(1.0 / [UIScreen mainScreen].scale);
        make.width.offset([UIScreen mainScreen].bounds.size.width);
    }];
    separatorView.backgroundColor = [UIColor colorWithHex:0xbebebe];
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [buttomMoreView addSubview: cancelBtn];
    
    [cancelBtn hm_setTitle:@"取消" andTiTleColorWithHex:0xffb33b forState:UIControlStateNormal];
    
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(separatorView.mas_bottom);
        make.left.right.bottom.offset(0);
    }];
    
    cancelBtn.tag = MoreButtonTypeBottomCancle;
    
    [cancelBtn addTarget:self action:@selector(clickButtomMoreViewBtn:) forControlEvents:UIControlEventTouchDown];

    return buttomMoreView;
}

#pragma mark - 触发事件

- (void)clickPlayBtn:(UIButton *)sender
{
    if(self.playState)
    {
        [self stop];
    }
    else
    {
        [self play];
        
    }
}

- (void)clickLeft15SecondBtn:(UIButton *)sender
{
    [self rightSeek15];
}

- (void)clickRight15SecondBtn:(UIButton *)sender
{
    [self leftSeek15];
}

- (void)clickPreviousBtn:(UIButton *)sender
{
    [self playPrevious];
}

- (void)clickNextBtn:(UIButton *)sender
{
    [self playNext];
}

- (void)changeProgress:(UISlider *)sender
{
    [self.player seekToTime:CMTimeMake(sender.value * self.player.currentTime.timescale, self.player.currentTime.timescale)];
}

- (void)updateRateAction:(UIButton *)btn
{
    NSArray *titleArray = @[@"正常播放",@"2倍播放",@"0.5倍播放",@"0.7倍播放",@"1.5倍播放",@"1.25倍播放"];
    
    NSArray *imageArray = @[@"new_audio_rate1_btn",@"new_audio_rate2_btn",@"new_audio_rate05_btn",@"new_audio_rate07_btn", @"new_audio_rate15_btn", @"new_audio_rate125_btn"];
    
    [btn setImage:[UIImage imageNamed:imageArray[self.rateCondition]] forState:UIControlStateNormal];
    
    self.rateLabel.text = titleArray[self.rateCondition];
}

#pragma mark - 事件
#pragma mark 下部按钮事件
- (void)clickTabBarViewBtn:(UIButton *)sender
{
    switch (sender.tag)
    {
        case 0:
        {
            HMAudioPlayerListViewController * listViewController = [[HMAudioPlayerListViewController alloc]init];
            
            listViewController.modelArray = self.modelArray;
            
            listViewController.finishSelectBlock = ^(NSIndexPath *indexPath)
            {
                if(indexPath.row < self.modelArray.count)
                {
                    [self playWithIndex:indexPath.row];
                }
            };
        
            [self mo_presentViewController:listViewController animated:YES completion:nil];
            
        }break;
        case 1:
        {
            HMAudioPlayerTextViewController *textViewController = [[HMAudioPlayerTextViewController alloc]init];
            [self mo_presentViewController:textViewController animated:YES completion:nil];
        }
            break;
        case 2:
        {
            //self.likeBtn.selected = !self.likeBtn.selected;
            // new_main_audio_liked_selected
            
        }break;
        case 3:
        {

            
        }break;
        case 4:
        {
            [self mo_presentContentView:[self installButtomMoreView] animated:YES completion:nil];
        }break;
    }
}

#pragma mark 更多按钮事件
- (void)clickButtomMoreViewBtn:(UIButton *)sender
{
    switch (sender.tag) {
        case MoreButtonTypeBottomCancle:
        {
            [self dismissViewControllerAnimated:YES completion:nil];
        }break;
        case MoreButtonTypeRate:
        {
            self.rateCondition = (self.rateCondition + 1) % kRateCount;
            NSArray *valueArray = @[@1,@2,@0.5,@0.7,@1.5,@1.25];
            NSNumber *number = valueArray[self.rateCondition];
        
            self.player.rate = number.floatValue;
            
            [self updateRateAction:sender];
        }break;
        case MoreButtonTypeTimer:
        {
            HMAudioPlayerAudioTimerController *timerController = [[HMAudioPlayerAudioTimerController alloc]init];
            
            [self mo_presentViewController:timerController option:BottomPop completion:^{
                
                timerController.clickBlock = ^(NSInteger index){
                    switch (index) {
                        case 0:
                            //
                            self.closeTotalTime = 30 * 60;
                            // 30分钟
                            break;
                        case 1:
                            // 60分钟
                            self.closeTotalTime = 60 * 60;
                            break;
                        case 2:
                            // 90分钟
                            self.closeTotalTime = 90 * 60;
                            break;
                        case 3:
                            // 播放当前音频再关闭
                            self.closeTotalTime = -1;
                            break;
                        case 4:
                            // 关闭倒计时
                            self.closeTotalTime = 0;
                            break;
                        default:
                        {
                            [self mo_dismissLastCompletion:nil];
                            
                        }break;
                    }
                    [self mo_dismissLastCompletion:nil];

                };
            }];
            
//            [self dismissViewControllerAnimated:YES completion:nil];
        }break;
        case MoreButtonTypeShare:
        {
            [self mo_dismissLastCompletion:^{
                
                HMAudioPlayerShareView *shareView = [[HMAudioPlayerShareView alloc]init];
                
                shareView.cancleBlock = ^
                {
                    [self mo_dismissLastCompletion:nil];
                };
                
                [self mo_presentContentView:shareView animated:YES completion:nil];
            }];
            
            //shareView.shareFriendBlock
            //shareView.shareWechatBlock
            
        }break;
            
        default:
        {
        
        }
            break;
    }
}

#pragma mark - 功能
#pragma mark - 播放器功能部分

- (void)leftSeek15;
{
    float sec = CMTimeGetSeconds((self.player.currentTime)) - 15;
    if(sec <= 0)
    {
        [self.player seekToTime:kCMTimeZero];
    }
    else
    {
        [self.player seekToTime:CMTimeMake(sec * self.player.currentTime.timescale, self.player.currentTime.timescale)];
    }
}

- (void)rightSeek15;
{
    float sec = (float)CMTimeGetSeconds((self.player.currentTime)) + 15;
    if(sec >= (float)CMTimeGetSeconds((self.player.currentItem.duration)))
    {
        [self.player seekToTime:self.player.currentItem.duration];
    }
    else
    {
        [self.player seekToTime:CMTimeMake(sec * self.player.currentTime.timescale, self.player.currentTime.timescale)];
    }
}

- (NSInteger)listCount
{
    return _modelArray.count;
}

- (void)play
{
    if(self.playingModel == self.modelArray[_audioIndex])
    {
        [self.player play];
        [self.timer setFireDate:[NSDate dateWithTimeIntervalSinceNow:0]];
    }
    else
    {
        [self updateAudioPlayer];
    }
    self.playState = YES;
    [self playNotification];
    
}

- (void)playNotification
{
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    
    NSDictionary *userInfo = @{@"PLAYER_STATE":@(self.isPlaying)};
    
    [center postNotificationName:@"AUDIO_PLAYER_NOTIFICATION" object:nil userInfo:userInfo];
}

- (void)playWithIndex:(NSInteger)index
{
    if(index >= 0 && index < self.modelArray.count)
    {
        _audioIndex = index;
        
    }
    [self updateAudioPlayer];
    self.playState = YES;
    [self playNotification];
}

- (void)stop
{
    [self.timer setFireDate:[NSDate distantFuture]];
    [self.player pause];
    self.playState = NO;
    [self playNotification];
}

- (void)playPrevious;
{
    
    if(_audioIndex > 0)
    {
        _audioIndex --;
        [self updateAudioPlayer];
        return;
    }
    [self showHudAuto:@"已经是第一个"];
    
}

- (void)playNext
{
    
    if(_audioIndex < _modelArray.count - 1)
    {
        _audioIndex ++;
        [self updateAudioPlayer];
        return;
    }
    [self showHudAuto:@"已经是最后一个"];
}

#pragma mark - 处理中断功能
-(void)handleInterreption:(NSNotification *)sender
{
    if(self.isPlaying)
    {
        [self stop];
    
    }
    else
    {
        [self play];
    }
}

#pragma mark 关闭倒计时功能

-(void)setCloseTotalTime:(CGFloat)closeTotalTime
{
    _closeTotalTime = closeTotalTime;
    
    if(!self.closeTimer || !self.closeTimer.isValid)
    {
        self.closeTimer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(updateCloseTime) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:self.closeTimer forMode:NSRunLoopCommonModes];
    }
    
    if(closeTotalTime <= 0)
    {
        if(self.closeTimer)
        {
            [self.closeTimer invalidate];
        }
        [self updateCloseTime];
    }
    
}

- (void)updateCloseTime
{
    if (self.closeTotalTime > 0)
    {
        self.closeTotalTime --;
        self.timerLabel.text = [NSString convertMin:self.closeTotalTime];
        self.timerLabel.textColor = [UIColor colorWithHex:0xffa42f];
        return;
    }
    
    if(self.closeTotalTime == 0)
    {
        [self.closeTimer invalidate];
        [self stop];
        self.timerLabel.text = @"定时关闭";
        self.timerLabel.textColor = [UIColor colorWithHex:0xbebebe];
        return;
    }
    
    if(self.closeTotalTime < 0)
    {
        [self.closeTimer invalidate];
        self.timerLabel.text = @"播完这条";
        self.timerLabel.textColor = [UIColor colorWithHex:0xbebebe];
        return;
    }
}
@end


